package com.demo.freemarker.common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.demo.freemarker.vo.BaseVo;

public class ConnectOracle {
	/**
	 * 使用JDBC方式连接数据库,组装好数据并且存入map
	 * 
	 * @param driver 驱动类
	 * @param url	数据库连接URL
	 * @param username 用户名
	 * @param password 密码
	 * @return map 
	 */
	public static Map<String, Map<String, Params>> connect(BaseVo vo, String sql) {
    try {
        //加载驱动类
        Class.forName(vo.getDriver());
    }catch (ClassNotFoundException e1) {
        e1.printStackTrace();
    }
    //将各种流放入try()中，将由try来执行close()操作
    try (Connection con  = DriverManager.getConnection(vo.getUrl(), vo.getUsername(), vo.getPassword());
    	PreparedStatement ps = con.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
    ) {

            Map<String, Map<String, Params>> map = new LinkedHashMap<String, Map<String, Params>>();
            Map<String, Params> mapCommon = new LinkedHashMap<String, Params>();
                        int i = 0;
            while (rs.next()) {
                String tableName = rs.getString("table_name");
                String className = tableName.replaceAll("_", "");
                String columnName = rs.getString("column_name");
                String type = rs.getString("column_type");
                String key = String.valueOf(rs.getInt("pkey"));
                if(type.startsWith("DATE")) {
                	type = "DATE";
                }
                if(null != key || "null".equals(key)) {
                	if ("1".equals(key)) {
                		key = "Y";
                	} else {
                		key = "N";
                	}
                } else {
                	key = "";
                }
                String comment = rs.getString("column_comment");
                
                String bz = "";
                String sf = rs.getString("column_default");
                if("Y".equals(sf)) {
                	sf = "N";
                } else {
                	sf = "Y";
                }
                
                
                if (null != comment) {
                	comment = comment.replaceAll("\r|\n", "");
                	String[] arr = comment.trim().split(" ");
                	if (arr.length > 1) {
                    	for (int i1 = 1; i1 < arr.length; i1++) {
							bz += arr[i1];
						}
                    }
                	comment = arr[0];
                }
                //type = sqlTypeToJavaType(type);
                // 使首字母大写
                String classNameUpCase = FreemarkUtil.toUpString(className);
                String columnNameUpCase = FreemarkUtil.toUpString(columnName);
                //这里只是使用一个实体类接收ResultSet的结果
                Params p = new Params.Build()
                        .column(columnName.toUpperCase())
                        .comment(comment != null ? comment : "")
                        .defaultName(sf)
                        .type(type)
                        .bz(bz)
                        .key(key)
                        .tableName(tableName)
                        .className(className).classNameUpCase(classNameUpCase)
                        .columnNameUpCase(columnNameUpCase)
                        .buildParams();
                //将每一个组装好的实体类存入MAP，指定key
                mapCommon.put("Params" + i, p);
                i++;
            }
            //全部的MAP
            map.put("Paramss", mapCommon);
            System.out.println(map);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
}
	
	public static String sqlTypeToJavaType (String type) {
		type = type.replace("(", ",").split(",")[0].toUpperCase();
		switch (type) {
		
		case "VARCHAR":
			return "String";
			
		case "CHAR":
			return "String";
			
		case "DATETIME":
			return "Date";
			
		case "DATE":
			return "Date";
			
		case "NUMBER":
			if (type.split(",").length > 0) {
				return "Double";
			}
			return "Integer";
			
		case "INT":
			return "Integer";
			
		default:
			return "";
		}

	}
	
	/**

	 * @param type

	 *            java中的类型

	 * @return mySql中的数据类型

	 * @Description 描述:把传进来的java类型，类型转换为数据库中的类型

	 */

	public static String javaType2MySqlType(Entry<String, String> entry) {

		String javaType = "";

		if (entry.getValue().contains(".")) {
			// 类型的截取
			int lastIndexOf = entry.getValue().lastIndexOf(".");
			javaType = entry.getValue().substring(lastIndexOf + 1);

		} else {

			javaType = entry.getValue();

		}

		switch (javaType) {
		
			case "String":
				return entry.getKey() + " VARCHAR(255) ,";
	
			case "byte[]":
				return entry.getKey() + " BLOB ,";
	
			case "int":
				return entry.getKey() + " INTEGER ,";
	
			case "Integer":
				return entry.getKey() + " INTEGER ,";
	
			case "Boolean":
				return entry.getKey() + " BIT ,";
	
			case "boolean":
				return entry.getKey() + " BIT ,";
	
			case "Long":
				return entry.getKey() + " BIGINT ,";
	
			case "long":
				return entry.getKey() + " BIGINT ,";
	
			case "float":
				return entry.getKey() + " FLOAT ,";
	
			case "Float":
				return entry.getKey() + " FLOAT ,";
	
			case "double":
	
				return entry.getKey() + " DOUBLE ,";
	
			case "Double":
	
				return entry.getKey() + " DOUBLE ,";
	
			case "BigDecimal":
				return entry.getKey() + " DECIMAL ,";
	
			case "Date":
				return entry.getKey() + " DATETIME,";
	
			default:
				return entry.getKey() + "_id Long,";
		}

	}

 
}
